import storageUtil from './localstorage';

const tokenUtil = {
  // Set a token with its name and value, with optional expiration time
  setToken(tokenName: string, tokenValue: string, expireInSeconds?: number) {
    const tokenObj = { name: tokenName, value: tokenValue };

    if (expireInSeconds) {
      storageUtil.set({
        key: 'authToken', // Use token name as the key
        value: tokenObj, // Store the token object
        expire: `${expireInSeconds}s`, // Expire time in seconds
      });
    } else {
      // Store the token object without expiration
      storageUtil.set({
        key: tokenName,
        value: tokenObj,
      });
    }
  },

  // Get a token by its name
  getToken() {
    const tokenData = storageUtil.get('authToken');

    // If token exists and has not expired, return it, else return null
    if (tokenData && tokenData.value) {
      return tokenData.value; // { name, value }
    } else {
      return null;
    }
  },

  // Remove a token by its name
  removeToken() {
    storageUtil.delete('authToken');
  },
};

export default tokenUtil;
